import Fastify from 'fastify';
import cors from 'fastify-cors';
import { MongoClient, Db } from 'mongodb';
import { ClientTelemetry } from '@sodache/shared';
import { HealthDTO, TelemetryDTO } from '@sodache/shared';

const fastify = Fastify({ logger: true });
fastify.register(cors, { origin: true });

const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017';
const DB_NAME = process.env.DB_NAME || 'sodache';

let db: Db | null = null;

async function connectMongo() {
  const client = new MongoClient(MONGODB_URI);
  await client.connect();
  db = client.db(DB_NAME);
  fastify.log.info(`Connected to MongoDB: ${DB_NAME}`);
}

fastify.get('/health', async (): Promise<HealthDTO> => {
  return { status: 'ok' };
});

fastify.post('/telemetry', async (request, reply): Promise<TelemetryDTO> => {
  const body = request.body as ClientTelemetry | ClientTelemetry[];
  if (!db) {
    reply.code(503);
    return { ok: false };
  }
  const docs = Array.isArray(body) ? body : [body];
  await db.collection('telemetry').insertMany(
    docs.map((d) => ({ ...d, _ts: new Date() })),
  );
  return { ok: true };
});

const PORT = Number(process.env.PORT || 3000);

connectMongo()
  .then(() => fastify.listen({ port: PORT, host: '0.0.0.0' }))
  .catch((err) => {
    fastify.log.error(err);
    process.exit(1);
  });
